package com.yb.framework.security.handler;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import com.yb.common.constant.Constants;
import com.yb.common.utils.DateUtil;
import com.yb.common.utils.IpUtil;
import com.yb.common.utils.SnowflakeIdWorker;
import com.yb.common.utils.StringUtil;
import com.yb.framework.security.utils.SecurityUtil;
import com.yb.project.system.domain.SysLogLogin;
import com.yb.project.system.service.SysLogLoginService;

@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
	
	@Autowired
	private SysLogLoginService sysLogLoginService;
	
	private RequestCache requestCache = new HttpSessionRequestCache();
	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	
	private final Logger logger = LoggerFactory.getLogger(AuthenticationSuccessHandlerImpl.class);	

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// 打印登录日志
		logger.info("用户[" + request.getParameter("username") + "]，登录系统成功");
		// 记录登录日志
		Date loginTime = new Date();
		SysLogLogin sysLogLogin = new SysLogLogin();
		sysLogLogin.setId(SnowflakeIdWorker.getInstance().getId());
		sysLogLogin.setLoginUser(SecurityUtil.getUsername());
		sysLogLogin.setMessage(SecurityUtil.getUsername() + " ，" + DateUtil.date2String(loginTime, null) + " 登录系统成功");
		sysLogLogin.setIpAddr(IpUtil.getIpAddr(request));
		sysLogLogin.setStatus(Constants.SUCCESS);
		sysLogLogin.setLoginTime(loginTime);
		sysLogLoginService.insertLogAsync(sysLogLogin);
		
		// 跳转到缓存页面；无缓存页面，跳转到首页
		String redirectUrl = "/index";
		SavedRequest savedRequest = requestCache.getRequest(request, response);
		if (savedRequest != null && StringUtil.isNotEmpty(savedRequest.getRedirectUrl())) {
			redirectUrl = savedRequest.getRedirectUrl();
		}
		redirectStrategy.sendRedirect(request, response, redirectUrl);
	}
}
